from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.orm import relationship

db = SQLAlchemy()


class User(db.Model):
    __tablename__ = 'users'
    id = db.Column(db.String(255), unique=True, primary_key=True)
    avatar = db.Column(db.String(255), default='')
    name = db.Column(db.String(80), nullable=False)
    phone = db.Column(db.String(120), nullable=False)
    password = db.Column(db.String(255), nullable=False, )

    def to_dict(self):
        return {
            'id': self.id,
            'name': self.name,
            'phone': self.phone,
            'avatar': self.avatar,
            'password': self.password,
        }


# 优惠券列表
class Coupon(db.Model):
    __tablename__ = 'coupon'  # 表名建议小写

    # 自增主键 (MySQL使用BIGINT对应BIGINT UNSIGNED AUTO_INCREMENT)
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)

    name = db.Column(db.String(100), nullable=False)  # 优惠券名称
    discount = db.Column(db.Integer, nullable=False)  # 折扣信息
    condition = db.Column(db.String(200), nullable=True)  # 使用条件
    time = db.Column(db.String(50), nullable=False)  # 有效期（字符串形式）
    cost = db.Column(db.Integer, nullable=False)  # 花费积分

    # 添加一对多关系
    user_coupons = relationship('UserCoupon', back_populates='coupon')

    def __repr__(self):
        return f'<Coupon {self.name}>'


# 用户优惠券
class UserCoupon(db.Model):
    __tablename__ = 'user_coupon'  # 表名建议小写

    # 自增主键 (MySQL使用BIGINT对应BIGINT UNSIGNED AUTO_INCREMENT)
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    user_id = db.Column(db.ForeignKey('user_points.user_id'))
    coupon_id = db.Column(db.ForeignKey('coupon.id'))

    # 定义关系属性
    user_points = relationship('UserPoints')
    coupon = relationship('Coupon')

    def __repr__(self):
        return f'<UserCoupon user:{self.user_id} coupon:{self.coupon_id}>'

    def to_dict(self):
        """返回包含优惠券详细信息的字典"""
        return {

            'name': self.coupon.name,
            'discount': self.coupon.discount,
            'condition': self.coupon.condition,
            'time': self.coupon.time,
            'cost': self.coupon.cost

        }


# 用户积分账户
class UserPoints(db.Model):
    __tablename__ = 'user_points'

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    user_id = db.Column(db.String(150), nullable=False)
    points = db.Column(db.Integer, nullable=False, default=0)

    def __repr__(self):
        return f'<UserPoints user_id={self.user_id}>'

    def to_dict(self):
        return {
            'user_id': self.user_id,
            'points': self.points,
        }


# 上一次公里数
class Mile(db.Model):
    __tablename__ = 'mile'
    user_id = db.Column(db.String(150), nullable=True, primary_key=True)
    miles = db.Column(db.Integer, nullable=False, default=0)

    def __repr__(self):
        return f'<Mile user_id={self.user_id}>'

    def to_dict(self):
        return {
            'user_id': self.user_id,
            'miles': self.miles,
        }
